﻿Add-Type -Assembly System.ServiceModel.Web, System.Runtime.Serialization

$utf8 = [System.Text.Encoding]::UTF8
$WebClient = New-Object System.Net.WebClient

$uriPrefix  = "http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q="
$uriPostfix = "&sl=en&tl=ru"

##--------------------------------------------------------------------------------
function Convert-JsonToXml
{
	param
	(
		[Parameter(ValueFromPipeline=$true)][string[]]$json
	)
	begin
	{
		$mStream = New-Object System.IO.MemoryStream
	}
	process
	{
		$bytes = $utf8.GetBytes($json)
		$mStream.Write($bytes, 0, $bytes.Length)
	}
	end
	{
		$mStream.Position = 0
		$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
		try
		{
			$xml = New-Object Xml.XmlDocument
			$xml.Load($jsonReader)
			$xml
		}
		finally
		{
			$jsonReader.Close()
			$mStream.Dispose()
		}
	}
}
##--------------------------------------------------------------------------------
function New-WordCard
{
	New-Object PSObject -Property @{
		"Text"         = ""
		"Phonetic"     = ""
		"Sound"        = ""
		"PartOfSpeech" = ""
		"Meaning"      = @{}
	}
}
##--------------------------------------------------------------------------------
function Update-WordCard
{
	param
	(
		[Parameter(ValueFromPipeline=$true)] $WordCard,
		[String] $Key,
		[String] $Value
	)
	switch ($Key)
	{
		"text" {
			$WordCard.Text = $Value
		}
		"phonetic" {
			$WordCard.Phonetic = $Value
		}
		"sound" {
			$WordCard.Sound = $Value
		}
		"part-of-speech" {
			$WordCard.Meaning.Add($Value, @())
			$WordCard.PartOfSpeech = $Value
		}
		"meaning" {
			$WordCard.Meaning[$WordCard.PartOfSpeech] += @($Value)
		}
	}
}
##--------------------------------------------------------------------------------
function Get-WordFromDictionary
{
	param
	(
		[Parameter(ValueFromPipeline=$true)]
		[String[]] $WordList
	)
	process
	{
		foreach ($Word in $input)
		{
			## Prepare word - trim text and replace spaces to '+' sign
			$Word = $Word.Trim() -replace "\s+", "+"
			## Create uri
			$uri = $uriPrefix + $Word + $uriPostfix
			## Get result in JSON format
			$json = $WebClient.DownloadString($uri)
			## Cut the JSON string
			$json = $json.Substring(25, $json.Length - 25 - 10) -replace "\\x[0-9a-f]{2}", ""
			## Convert JSON to XML
			$xml = Convert-JsonToXml $json

			## Process XML and generate CardList - array of Card
			$CardList = @()
			foreach ($primaries in $xml.root.primaries.'item')
			{
				if ($primaries -eq $null) { continue }
				$Card = New-WordCard
				foreach ($term in $primaries.terms.'item')
				{
					$Card | Update-WordCard -Key $term.SelectSingleNode("type").'#text' -Value $term.SelectSingleNode("text").'#text'
				}
				foreach ($entry in $primaries.entries.'item')
				{
					foreach ($label in $entry.labels.'item')
					{
						if ($label -eq $null) { continue }
						$Card | Update-WordCard -Key $label.SelectSingleNode("title").'#text' -Value $label.SelectSingleNode("text").'#text'
					}
					foreach ($term in $entry.terms.'item')
					{
						if ($term -eq $null) { continue }
						foreach ($label in $term.labels.'item')
						{
							if ($label -eq $null) { continue }
							$Card | Update-WordCard -Key $term.SelectSingleNode("text").'#text' -Value $label.SelectSingleNode("text").'#text'
						}
					}
					foreach ($subentry in $entry.entries.'item')
					{
						if ($subentry -eq $null) { continue }
						foreach ($term in $subentry.terms.'item')
						{
							$Card | Update-WordCard -Key $subentry.SelectSingleNode("type").'#text' -Value $term.SelectSingleNode("text").'#text'
						}
					}
				}
				$Card
			}
		}
	}
}
##--------------------------------------------------------------------------------

$Path = "C:\Users\dteselkin\Desktop\WordList.txt"

Get-Content -Path $Path |
	Get-WordFromDictionary | 
	ForEach-Object {
		foreach ($pos in $_.Meaning.Keys)
		{
			#$_.Meaning[$pos] -join ","
			#"<word>" + $_.Text + " /" + $pos + "/</word><transcription>" + $_.Phonetic + "</transcription>" + "<translation>" + ($_.Meaning[$pos] -join ",") + "<translation>"
			$_.Text + " /" + $pos + "/ " + $_.Phonetic
			$_.Meaning[$pos] -join ", "
		}
	} | Add-Content -Path "$Path.gl" #-Encoding UTF8


